import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/home'
import Login from '@/views/login'
import PowerloadDashboard from '@/views/powerload-dashboard'
import PredictionOverviewPage from '@/views/PredictionOverviewPage'
import NewPredictionOverviewPage from '@/views/NewPredictionOverviewPage'
import ErrorAnalysisPage from '@/views/ErrorAnalysisPage'
import UsagePatternsPage from '@/views/UsagePatternsPage'
import WeatherImpactPage from '@/views/WeatherImpactPage'
import HistoricalQueryPage from '@/views/HistoricalQueryPage'
import DataOverviewPage from '@/views/DataOverviewPage'
import ModelTrainingPage from '@/views/ModelTrainingPage'
import RealTimePredictionPage from '@/views/RealTimePredictionPage'

Vue.use(Router)

const router = new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/dashboard',
      name: 'Home',
      component: Home,
      meta: { requiresAuth: true }
    },
    // 独立页面路由
    {
      path: '/prediction-overview',
          name: 'PredictionOverview',
      component: PredictionOverviewPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/new-prediction-overview',
          name: 'NewPredictionOverview',
      component: NewPredictionOverviewPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/model-evaluation',
          name: 'ModelEvaluation',
      component: () => import('@/views/ModelEvaluationPage'),
      meta: { requiresAuth: true }
    },
    {
      path: '/error-analysis',
          name: 'ErrorAnalysis',
      component: ErrorAnalysisPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/usage-patterns',
          name: 'UsagePatterns',
      component: UsagePatternsPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/weather-impact',
          name: 'WeatherImpact',
      component: WeatherImpactPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/historical-query',
          name: 'HistoricalQuery',
      component: HistoricalQueryPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/data-overview',
          name: 'DataOverview',
      component: DataOverviewPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/model-training',
          name: 'ModelTraining',
      component: ModelTrainingPage,
      meta: { requiresAuth: true }
    },
    {
      path: '/real-time-prediction',
          name: 'RealTimePrediction',
      component: RealTimePredictionPage,
      meta: { requiresAuth: true }
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('access_token')
  
  console.log('🔍 路由守卫调试:', {
    to: to.path,
    from: from.path,
    token: token ? `${token.substring(0, 20)}...` : 'null',
    requiresAuth: to.matched.some(record => record.meta.requiresAuth)
  })
  
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要认证的路由
    if (!token) {
      console.log('❌ 无access_token，跳转到登录页')
      next('/login')
    } else {
      console.log('✅ 有access_token，允许访问')
      next()
    }
  } else {
    console.log('🔓 无需认证，直接访问')
    next()
  }
})

// 全局处理Vue Router的重复导航警告
const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace

Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      return Promise.reject(err)
    }
  })
}

Router.prototype.replace = function replace(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalReplace.call(this, location, onResolve, onReject)
  }
  return originalReplace.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      return Promise.reject(err)
    }
  })
}

export default router
